<?php


namespace Hooks;


use models\Exception\AbstractException;
use Yaf\Exception;
use Yaf\Plugin_Abstract;
use Yaf\Registry;
use Yaf\Request_Abstract;
use Yaf\Response_Abstract;
use youliPhpLib\Common\StringOperation;

class IpFilterMiddlewarePlugin extends Plugin_Abstract
{
    public function dispatchLoopStartup(Request_Abstract $request, Response_Abstract $response){
        // 获取当前客户端ip
        $client_ip = StringOperation::getIP();

        // 当前url是否需要ip过滤
        if (strpos(',' . Registry::get('config')['application']['ip']['filter']['url'] . ',', ',' . $request->getRequestUri() . ',') !== false &&
            $client_ip !== Registry::get('config')['application']['ip']['filter']['white_list']) {
            Registry::get('ip_log')->err('调用' . $request->getRequestUri() . '的调用者ip不在ip白名单中.调用者ip: ' . $client_ip);
            throw new Exception(AbstractException::INVALID_IP, AbstractException::SIGN_INVALID_NO);
        }

        // 判断请求admin模块或api模块的ip是否合法
        if ($request->getModuleName() === 'Admin' && $client_ip !== Registry::get('config')['application']['ip']['admin']['white_list']) {
            Registry::get('ip_log')->err('调用后台接口的ip不在ip白名单中.调用者ip: ' . $client_ip);
            throw new Exception(AbstractException::INVALID_IP, AbstractException::SIGN_INVALID_NO);
        }

        // 暂时注释，因为不知道相应支付通道异步或调货1688通知的服务器ip段
        // 判断请求notify模块的ip是否合法
        /*if ($request->getModuleName() === 'Notify' &&  strpos(Registry::get('config')['application']['ip']['notify']['white_list'], $client_ip) === false) {
            Registry::get('ip_log')->err('调用notify接口的ip不在ip白名单中.调用者ip: ' . $client_ip);
            throw new Exception(AbstractException::INVALID_IP, AbstractException::SIGN_INVALID_NO);
        }*/

    }

}
